package srzy.dao
import java.sql.DriverManager
import srzy.data.DBCompareInfo
import srzy.common.Config
import srzy.common.Logging
import scala.collection.mutable.ListBuffer
import srzy.common.Common

object DBOracle extends DBUtil with srzy.common.Logging {

  Class.forName(Config.getValue("root", "config", "CaseInfoSource", "Driver")) //"oracle.jdbc.driver.OracleDriver"
  val url = Config.getValue("root", "config", "CaseInfoSource", "URL") //"jdbc:oracle:thin:ocs/ocs@10.26.13.211:1522:TEST211"
  logger.debug("url:" + url)

  def getCaseInfo(): Map[String, List[DBCompareInfo]] = {
    logger.debug("getCaseInfo start")
    val sql = """SELECT A.CASE_ID,
       A.ORDER_ID,
       B.CHECK_CONTENT AS SQL,
       A.CHECK_PARA    AS PARA,
       A.PRE_RESULT
  FROM DCFMT_AUTO_CASE_CHECK_PARA A
  LEFT JOIN DCFMT_AUTO_CHECK_CONFIG B
    ON (A.CHECK_ID = B.CHECK_ID)
 WHERE B.CHECK_TYPE = 2
 ORDER BY A.CASE_ID, A.ORDER_ID"""
    logger.debug("sql:" + sql)
    def ifnull(s: String) = {
      if (s == null)
        ""
      else
        s
    }
    val conn = DriverManager.getConnection(url)
    try {
      val statement = conn.createStatement
      val rs = statement.executeQuery(sql)

      //      var m: java.util.Map[String, java.util.List[DBCompareInfo]] = new java.util.HashMap
      var m = scala.collection.mutable.Map[String, collection.mutable.ListBuffer[DBCompareInfo]]()
      while (rs.next()) {
        val caseName = ifnull(rs.getString(1))
        if (!m.contains(caseName))
          m.put(caseName, new collection.mutable.ListBuffer[DBCompareInfo])
        m.apply(caseName) += (new DBCompareInfo {
          oraderId = ifnull(rs.getString(2))
          originalSQL = ifnull(rs.getString(3))
          para = ifnull(rs.getString(4))
          preResult = ifnull(rs.getString(5))
        })
      }
      //      return l.foldLeft(collection.mutable.ListBuffer[(String, DBCompareInfo)])(l)
      m.toList.map(x => (x._1, x._2.toList)).toMap
      //      return l.toList
    } finally {
      conn.close
      logger.debug("getCaseInfo over")
    }
  }

  def getCaseInfo2(): List[(String, String)] = {
    logger.debug("get CaseInfo start")
    val sql = """SELECT CASE_PWD, EXCEPT_CONDITION FROM OCS_AUTO_CASE_OFFLINE WHERE DEAL_FLAG = 0 ORDER BY CASE_ID"""
    logger.debug("sql:" + sql)
    val conn = DriverManager.getConnection(url)
    try {
      val statement = conn.createStatement
      val rs = statement.executeQuery(sql)
      var lb = ListBuffer.empty[(String, String)]
      while (rs.next()) {
        lb.append((Common.ifnull(rs.getString(1)), Common.ifnull(rs.getString(2))))
      }
      lb.toList
    } finally {
      conn.close
      logger.debug("get CaseInfo over")
    }
  }

}